package com.mes.check.manager;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.mes.check.manager.iface.IWaixieCheckReportManager;
import com.mes.basicdata.dao.iface.IEmployeeDao;
import com.mes.basicdata.dao.iface.IWorkCenterDao;
import com.mes.basicdata.domain.Employee;
import com.mes.basicdata.domain.WorkCenter;
import com.mes.check.dao.iface.ICheckBillDao;
import com.mes.check.dao.iface.IDefectJudgeDao;
import com.mes.check.dao.iface.IRejectDao;
import com.mes.check.dao.iface.IConcessionDao;
import com.mes.check.dao.iface.IReworkDao;
import com.mes.check.dao.iface.IWaixieCheckReportDao;
import com.mes.check.domain.CheckBill;
import com.mes.check.domain.DefectJudge;
import com.mes.check.domain.DefectJudgeDetail;
import com.mes.check.domain.Reject;
import com.mes.check.domain.Concession;
import com.mes.check.domain.Rework;
import com.mes.check.domain.WaixieCheckReport;
import com.mes.common.domain.BasicModel;
import com.mes.common.manager.BasicManager;
import com.mes.inventory.dao.iface.IInvIODao;
import com.mes.inventory.domain.InvIO;
import com.mes.task.dao.iface.IOperationTaskDao;
import com.mes.task.dao.iface.IPartTaskDao;
import com.mes.task.domain.OperationTask;
import com.mes.task.domain.PartTask;

@Component
public class WaixieCheckReportManager extends BasicManager<WaixieCheckReport> implements IWaixieCheckReportManager {
	private final static Log log = LogFactory.getLog(WaixieCheckReportManager.class);

	@Autowired
	IWaixieCheckReportDao waixieCheckReportDao;
	@Autowired
	IPartTaskDao partTaskDao;
	@Autowired
	IOperationTaskDao operationTaskDao;
	@Autowired
	IWorkCenterDao workCenterDao;
	@Autowired
	IEmployeeDao employeeDao;
	@Autowired
	IInvIODao invIODao;
	@Autowired
	ICheckBillDao checkBillDao;
	@Autowired
	IDefectJudgeDao defectJudgeDao;
	@Autowired
	IReworkDao reworkDao;
	@Autowired
	IConcessionDao concessionDao;
	@Autowired
	IRejectDao rejectDao;

	private List<WaixieCheckReport> prepareWaixieCheckReports() {
		List<WaixieCheckReport> lstReport = new ArrayList();
		try {
			Calendar cal = Calendar.getInstance();
			cal.set(Calendar.YEAR, 2012);
			cal.set(Calendar.MONTH, 7);
			cal.set(Calendar.DAY_OF_MONTH, 3);

			cal.set(Calendar.DAY_OF_MONTH, 1);
			cal.set(Calendar.HOUR_OF_DAY, 0);
			cal.set(Calendar.MINUTE, 0);
			cal.set(Calendar.SECOND, 1);
			Date fromDate = cal.getTime();
			// long
			// nDay=(fromDate.getTime()/(24*60*60*1000)+1-570)*(24*60*60*1000);
			// fromDate.setTime(nDay);

			cal.set(Calendar.DAY_OF_MONTH, 30);
			cal.set(Calendar.HOUR_OF_DAY, 23);
			cal.set(Calendar.MINUTE, 59);
			cal.set(Calendar.SECOND, 59);
			Date toDate = cal.getTime();
			// nDay=(toDate.getTime()/(24*60*60*1000)+1-560)*(24*60*60*1000);
			// toDate.setTime(nDay);

			log.error("fromDate---> " + fromDate.toLocaleString());
			log.error("toDate---> " + toDate.toLocaleString());
			// List<PartTask> partTaskList =
			// partTaskDAO.getWaixiePartTasksByReturnTime(fromDate, toDate);
			List<PartTask> partTaskList = waixieCheckReportDao.getNeedSyncWaixiePartTasksByTime(fromDate, toDate);
			if (partTaskList != null) {
				log.error("今日入库外协零件任务数量：" + partTaskList.size());
				for (PartTask parttask : partTaskList) {
					log.error("零件：" + parttask.getTaskUid() + "/" + parttask.getBigModel() + "/"
							+ parttask.getPart().getDrawingId() + "/" + parttask.getPart().getPartName() + "/"
							+ parttask.getBatchNum());

					List<OperationTask> operationTaskList = operationTaskDao
							.getWaixieOperationTasksByPartTaskUid(parttask.getTaskUid());
					Map<String, List> waixieDeptMap = new HashMap<String, List>();
					List<OperationTask> lstTemp = null;
					if (operationTaskList != null) {
						for (OperationTask operationTask : operationTaskList) {
							// System.out.println("工序唯一号："+operationTask.getTaskUid());
							String workCenterUid = operationTask.getWorkCenterUid();
							if (!waixieDeptMap.containsKey(workCenterUid)) {
								lstTemp = new ArrayList();
								lstTemp.add(operationTask);
								waixieDeptMap.put(workCenterUid, lstTemp);
							} else {
								lstTemp = (List<OperationTask>) waixieDeptMap.get(workCenterUid);
								lstTemp.add(operationTask);
							}
						}
					}

					for (Map.Entry<String, List> entry : waixieDeptMap.entrySet()) {
						String workCenterUid = entry.getKey();
						WorkCenter workCenter = workCenterDao.getById(workCenterUid);
						// System.out.println("外协单位："+workCenter.getWorkCenterName());

						WaixieCheckReport report = waixieCheckReportDao.getWaixieCheckReport(parttask.getTaskUid(),
								workCenterUid);
						if (report == null) {
							report = new WaixieCheckReport();
							report.setUniqueId(java.util.UUID.randomUUID().toString());
							report.setCreateTime(new Date());
							report.setPartTaskUid(parttask.getTaskUid());
							report.setBigModel(parttask.getBigModel());
							report.setModel(parttask.getModel());
							report.setDrawingId(parttask.getPart().getDrawingId());
							report.setPartName(parttask.getPart().getPartName());
							report.setBatchNum(parttask.getBatchNum());
							report.setCoDeptId(workCenterUid);
							report.setCoDeptName(workCenter.getWorkCenterName());
							report.setObjectState(BasicModel.OBJECTSTATE_TOBEADDED);
						} else {
							report.setObjectState(BasicModel.OBJECTSTATE_TOBEUPDATED);
						}

						List<OperationTask> lstOperationTask = entry.getValue();
						String strOperation_IdDescs = "";
						OperationTask lastOperationTask = null;
						for (OperationTask operationTask : lstOperationTask) {
							strOperation_IdDescs = strOperation_IdDescs + operationTask.getOperationIdDesc() + ",";
							lastOperationTask = operationTask;
						}
						// 加工工序
						report.setOperationIdDescs(strOperation_IdDescs);

						if (lastOperationTask != null) {
							report.setSendQty(lastOperationTask.getPlanQty());
							// 交检数
							report.setSubmitCheckQty(lastOperationTask.getPlanQty());
							// //合格数
							// report.setPassQty(lastOperationTask.getPlanQty()-lastOperationTask.getRejectQty());

							List<InvIO> lstInvIo = invIODao.getInvIosByTaskUidIOType(lastOperationTask.getTaskUid(),
									106);
							if (lstInvIo != null) {
								for (InvIO invio : lstInvIo) {
									report.setActBackTime(invio.getIoDate());
								}
							}

							List<CheckBill> lstCheck2 = checkBillDao.getCheckBillsByTaskUidCheckType(lastOperationTask.getTaskUid(),
									33);
							if (lstCheck2 != null) {
								for (CheckBill check : lstCheck2) {
									// 检验员
									report.setCheckerUid(check.getCheckerUid());
									Employee e = employeeDao.getById(check.getCheckerUid());
									report.setCheckerName(e.getEmployeeName());

									if ("1".equalsIgnoreCase(check.getCheckCount())) {
										// 自身发现不合格数
										report.setBeforeCheckDefectQty(check.getDefectQtyBeforeCheck() != null
												? check.getDefectQtyBeforeCheck() : 0);
										// 一次交检合格数
										if (check.getDefectQty() != null) {
											report.setFirstCheckPassQty(
													lastOperationTask.getPlanQty() - check.getDefectQty());
										} else {
											report.setFirstCheckPassQty(lastOperationTask.getPlanQty());
										}

										break;
									}
								}
							}

							List<CheckBill> lstCheck = checkBillDao.getCheckBillsByTaskUidCheckType(lastOperationTask.getTaskUid(),
									32);
							if (lstCheck != null) {
								for (CheckBill check : lstCheck) {
									// 检验员
									report.setCheckerUid(check.getCheckerUid());
									Employee e = employeeDao.getById(check.getCheckerUid());
									report.setCheckerName(e.getEmployeeName());

									if ("1".equalsIgnoreCase(check.getCheckCount())) {
										// 自身发现不合格数
										report.setBeforeCheckDefectQty(check.getDefectQtyBeforeCheck() != null
												? check.getDefectQtyBeforeCheck() : 0);
										// 一次交检合格数
										if (check.getDefectQty() != null) {
											report.setFirstCheckPassQty(
													lastOperationTask.getPlanQty() - check.getDefectQty());
										} else {
											report.setFirstCheckPassQty(lastOperationTask.getPlanQty());
										}

										break;
									}
								}
							}

							List<DefectJudge> lstJudge = defectJudgeDao
									.getDefectJudgesByTaskUid(lastOperationTask.getTaskUid());
							if (lstJudge != null) {
								for (DefectJudge judge : lstJudge) {
									// 检验员
									report.setCheckerUid(judge.getChecker().getUuid());
									report.setCheckerName(judge.getChecker().getEmployeeName());
									// 审理单号
									report.setDefectJudgeBillNumber(judge.getBillNumber());

									float rejectQty = 0;
									float reworkQty = 0;
									float repairQty = 0;
									if (judge.getDefectJudgeDetails().size() > 0) { // 如果审理单中记录了审理结果
										for (DefectJudgeDetail detail : judge.getDefectJudgeDetails()) {
											if (DefectJudge.JUDGE_RESULT_REJECT.equals(detail.getJudgeResult())
													|| DefectJudge.JUDGE_RESULT_ADVISE_REJECT
															.equals(detail.getJudgeResult())) {
												rejectQty = rejectQty + detail.getDefectQty();
											}
											if (DefectJudge.JUDGE_RESULT_REPAIR.equals(detail.getJudgeResult())
													|| DefectJudge.JUDGE_RESULT_ADVISE_REPAIR
															.equals(detail.getJudgeResult())) {
												repairQty = repairQty + detail.getDefectQty();
											}
											if (DefectJudge.JUDGE_RESULT_REWORK.equals(detail.getJudgeResult())
													|| DefectJudge.JUDGE_RESULT_ADVISE_REWORK
															.equals(detail.getJudgeResult())) {
												reworkQty = reworkQty + detail.getDefectQty();
											}
										}
									} else { // 如果审理单中没有记录结果，则直接查找该审理单是否有返工、让步、报废单
										List<Reject> lstReject = rejectDao.getRejectsByDefectJudgeUid(judge.getUuid());
										if (lstReject != null) {
											for (Reject reject : lstReject) {
												rejectQty = rejectQty + reject.getRejectQty();
											}
										}

										List<Concession> lstConcession = concessionDao.getConcessionBillsByDefectJudgeUid(judge.getUuid());
										if (lstConcession != null) {
											for (Concession concession : lstConcession) {
												repairQty = repairQty + concession.getConcessionQty();
											}
										}

										List<Rework> lstRework = reworkDao.getReworksByDefectJudgeUid(judge.getUuid());
										if (lstRework != null) {
											for (Rework rework : lstRework) {
												reworkQty = reworkQty + rework.getReworkQty();
											}
										}
									}

									// 报废数
									report.setRejectQty(rejectQty);
									// 让步数：
									report.setRepairQty(repairQty);
									// 返工数
									report.setReworkQty(reworkQty);
									// 合格数
									report.setPassQty(
											lastOperationTask.getPlanQty() - rejectQty - repairQty - reworkQty);
								}
							}
						}

						lstReport.add(report);
					}
				}
			} else {
				log.error("今日入库外协零件任务列表为空值");
			}
			// System.out.println("数据整理完成");
		} catch (Exception e) {
			log.error("prepareWaixieCheckReports外协更新定时器错误", e);

		}

		return lstReport;
	}

	private void saveWaixieCheckReport(List<WaixieCheckReport> lst) {
		try {
			for (WaixieCheckReport report : lst) {
				waixieCheckReportDao.save(report);
				// waixieCheckReportDAO.add(report);
				// waixieCheckReportManager.add(report);
			}
			log.error("数据保存成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			log.error("saveWaixieCheckReport外协更新定时器错误", e);
		}

	}

	/**
	 * 更新外协检验报表数据
	 */
	@Override
	public void updateWaiXieCheckReport() {
		log.error("开始更新外协检验报表数据。。。。。。");
		try {
			List<WaixieCheckReport> lst = this.prepareWaixieCheckReports();
			this.saveWaixieCheckReport(lst);
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			log.error("。。。。。。更新外协检验报表数据完成");
			e.printStackTrace();
		}
		log.error("。。。。。。更新外协检验报表数据完成");
	}

}
